package com.rlz.net.converter

import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.reflect.TypeToken
import okio.IOException
import org.paradisehell.convex.transformer.ConvexTransformer
import java.io.InputStream
import kotlin.jvm.Throws

/**
 * Created by RLZ
 * on 2021/9/16
 *
 */
class BaseConvexTransformer : ConvexTransformer {
    private val gson = Gson()


    @Throws(IOException::class)
    override fun transform(original: InputStream): InputStream {
        //反序列化为BaseResponse
        val response = gson.fromJson<BaseResponse<JsonElement>>(
            original.reader(),
            object : TypeToken<BaseResponse<JsonElement>>() {
            }.type
        )

        //判断是否成功
        if (response.errorCode == 0 && response.data != null)
            return response.data.toString().byteInputStream()


        throw java.io.IOException(
            "errorCode : " + response.errorCode + " ; errorMsg : " + response.errorMsg
        )
    }

}